
let departmentlistModule = (function(){
    let $tbody = $('tbody'),
        $edit = $('.w20>a')[0],
        $delete = $('.w20>a')[1];
    
    //部门列表绑定
    async function getlist(){
        let result = await axios.get('/department/list'),
            str = '';
        if(result.code==0){
            result.data.forEach((item,index)=>{
                str+=`<tr>
				<td class="w10">${item.id}</td>
				<td class="w20">${item.name}</td>
				<td class="w40">${item.desc}</td>
				<td class="w20" departmentId="${item.id}">
					<a href="javascript:;">编辑</a>
					<a href="javascript:;">删除</a>
				</td>
			</tr>`;
            })
        }
        $tbody.html(str);
    }
    //基于时间委托处理编辑和删除
    function delegate(){
        $tbody.click(async ev=>{
            let target = ev.target||window.event.target,
                $target = $(target),//转为jQuery对象
                TAG = target.tagName,
                TEXT = target.text;
            if(TAG==='A'){
                let departmentId = $target.parent().attr('departmentId');
                if(TEXT==='编辑'){
                    window.location.href = `departmentadd.html?departmentId=${departmentId}`;
                    return;
                }
                if(TEXT==='删除'){
                    let flag = confirm(`确定删除编号为【${departmentId}】的部门信息吗？无法撤销哦！`)
                    if(!flag) return;
                    let result = await axios.get('/department/delete',{
                        params:{
                            departmentId
                        }
                    });
                    if(result.code==0){
                        alert('此条信息已删除');
                        $target.parent().parent().remove();
                        return;
                    }
                }
                alert('网络繁忙，请稍后重试');
                return;
            }

        })
    }

    return {
        init(){
            getlist();
            delegate();
        }
    }
})();
departmentlistModule.init();